package com.erp.controller.user;

import com.erp.bean.User;
import com.erp.service.UserService;
import com.erp.utils.ExceptionUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author tj
 * @Date 2022-05-25 15:21:48
 */
public class AddUserServlet extends HttpServlet {
    UserService userService = new UserService();
    ExceptionUtil exceptionUtil = new ExceptionUtil();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charaset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        System.out.println(username);
        System.out.println(password);
        System.out.println(sex);
        System.out.println(phone);
        System.out.println(email);
        // 1.拿到用户去查询，这个用户是不是存在数据库中
        // 2.判断如果存在，抛出异常，如果不存在，保存
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setSex(sex);
        user.setPhone(phone);
        try {
            userService.saveUser(user);
            resp.sendRedirect(req.getContextPath() + "/doUserList");

        }catch (Exception e){
            exceptionUtil.error(e.getMessage(),"doUserList",this.getServletContext(), req, resp);
        }
//        super.doPost(req, resp);
    }
}